package T;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 筛选
 * 注意Person里面的链式调用
 */
public class Stream2 {
    public static void main(String[] args) {
        ArrayList<Person> ArrayList = new ArrayList<>();
        ArrayList.add(new Person("a", 20, 2000));
        ArrayList.add(new Person("b", 21, 3000));
        ArrayList.add(new Person("c", 22, 4000));
        ArrayList.add(new Person("d", 23, 5000));
        ArrayList.add(new Person("d", 24, 6000));
//        ArrayList.add(new Person("f", 24, null));

        //筛选，且返回list
        List<String> list = ArrayList.stream().filter(p -> p.getAge() > 21).filter(p -> p.getSalary() > 2000)
                .map(Person::getName).toList();
        //返回set格式，并且去重
        Set<String> collect = ArrayList.stream().map(person -> person.getName()).collect(Collectors.toSet());
        System.out.println("返回age>21 and salary>2000  " + list);
        System.out.println("去重返回名字  " + collect);
/**
 * 返回map格式并且进行筛选
 * 此时如果key值有相同的，必须进行(oldValue, newValue) -> newValue)，对value进行保留，不然会报错
 */
        Map<String, Person> map = ArrayList.stream().filter(p -> p.getSalary() > 3000)
                .collect(Collectors.toMap(Person::getName, p -> p, (oldValue, newValue) -> newValue));
        System.out.println(map);
/**
 * 如果Person中value存在空，则toMap会报错=
 * 如果想进行除重。且保留null可以试下下面的方法
 */
        ArrayList.add(new Person("f", 24, null));
        HashMap<String, Integer> HashMap = new HashMap<>();
        ArrayList.forEach(person -> HashMap.put(person.getName(), person.getSalary()));
        System.out.println(HashMap);
    }
}


class Person {
    private String name;
    private Integer age;
    private Integer Salary;

    public Person(String name, Integer age, Integer salary) {
        this.name = name;
        this.age = age;
        Salary = salary;
    }

    //构造函数的链式调用（this()）
    public Person(String name) {
        this(name, 60, 2000); // 默认age18,salary 1000
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSalary() {
        return Salary;
    }

    public void setSalary(Integer salary) {
        Salary = salary;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", Salary=" + Salary +
                '}';
    }
}

